package com.linksoul.service;


import com.linksoul.domain.CertificateRequest;
import com.linksoul.mapper.CertificateRequestMapper;

import com.linksoul.utils.CertificateNoGenerator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
public class CertificateService {

    private final CertificateRequestMapper certificateRequestMapper;

    public CertificateService(CertificateRequestMapper certificateRequestMapper) {
        this.certificateRequestMapper = certificateRequestMapper;
    }

    /**
     * 生成证书并保存关联关系
     */
    @Transactional
    public String generateCertificate(String requestId, String userId, String businessType) {
   try {
       // 检查requestId是否已存在
       CertificateRequest exist = certificateRequestMapper.selectByRequestId(requestId);
       if (exist != null) {
           return exist.getCertificateNo();
       }

       // 生成证书编号
       String certNo = CertificateNoGenerator.generate();

       // 构建扩展信息
       Map<String, Object> extInfo = new HashMap<>();
       extInfo.put("generateMethod", "auto");
       extInfo.put("version", "1.0");

       // 保存关联关系
       CertificateRequest mapping = new CertificateRequest();
       mapping.setRequestId(requestId);
       mapping.setCertificateNo(certNo);
       mapping.setUserId(userId);
       mapping.setBusinessType(businessType);
       mapping.setStatus(1);
       mapping.setExtInfo(extInfo);

       certificateRequestMapper.insert(mapping);

       return certNo;
   }catch (Exception e) {
       e.printStackTrace();
   }
   return null;
    }

    /**
     * 根据requestId查询证书编号
     */
    public String getCertificateByRequestId(String requestId) {
        CertificateRequest mapping = certificateRequestMapper.selectByRequestId(requestId);
        return mapping != null ? mapping.getCertificateNo() : null;
    }

    /**
     * 根据证书编号查询请求信息
     */
    public CertificateRequest getRequestByCertificateNo(String certificateNo) {
        return certificateRequestMapper.selectByCertificateNo(certificateNo);
    }
}
